<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="db.RetreqDAO"%>
<%@page import="db.Retreq"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="db.Retmat"%>
<%@page import="db.RetmatDAO"%>
<%@page import="db.Outreq"%>
<%@page import="db.OutpurmatDAO"%>
<%@page import="db.Outpurmat"%>
<%
	WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
	RetreqDAO retreqDao = (RetreqDAO)ctx.getBean("RetreqDAO");
	RetmatDAO retmatDao = (RetmatDAO)ctx.getBean("RetmatDAO");
	OutpurmatDAO outpurmatDao = (OutpurmatDAO)ctx.getBean("OutpurmatDAO");

	String reqCode = request.getParameter("reqCode");
	String reqDate = request.getParameter("reqDate");
	String tobId = request.getParameter("tobId");
	String outreqId = request.getParameter("outreqId");
	String maUserId = request.getParameter("maUserId");
	
	int tid = (Integer)session.getAttribute("tid");
	int uid = (Integer)session.getAttribute("id");
	
	Retreq retreq = new Retreq();
	retreq.setPhase(2);
	retreq.setMaState(1);
	retreq.setOutreqId(Integer.parseInt(outreqId));
	retreq.setReqDate(new SimpleDateFormat("yyyy-MM-dd").parse(reqDate));
	retreq.setReqUserDate(new Date());
	retreq.setReqUserId(uid);
	retreq.setTeamId(tid);
	retreq.setTobId(Integer.parseInt(tobId));
	if(maUserId != null && !"".equals(maUserId.trim())){
		retreq.setMaUserId(Integer.parseInt(maUserId));
	}
	retreqDao.save(retreq);
	
	retreq.setReqCode("T" + retreq.getId());
	retreqDao.attachDirty(retreq);
	
	String[] indexs = request.getParameterValues("indexs");
	String[] outpurmatIds = request.getParameterValues("outpurmatIds");
	String[] numbers = request.getParameterValues("numbers");
	if(indexs != null && indexs.length > 0)
	for(int i=0;i<indexs.length;i++){
		int index = Integer.parseInt(indexs[i]);
		Retmat retmat = new Retmat();
		retmat.setDate(new Date());
		retmat.setOutpurmatId(Integer.parseInt(outpurmatIds[index]));
		retmat.setRetNum(Integer.parseInt(numbers[index]));
		retmat.setRetreqId(retreq.getId());
		retmat.setState(1);
		retmatDao.save(retmat);
		
		Outpurmat outpurmat = outpurmatDao.findById(Integer.parseInt(outpurmatIds[index]));
		outpurmat.setRetUseNum(outpurmat.getRetUseNum() - Integer.parseInt(numbers[index]));
		outpurmatDao.attachDirty(outpurmat);
	}
	
	request.setAttribute("reqCode",retreq.getReqCode());
	request.setAttribute("info","success");
	pageContext.forward("/vm/returnStock/retApp_1.vm");
%>